//
//  ETSignedOutAlertController.swift
//  SwiftDemo2
//
//  Created by ShareAnimation on 2017/11/1.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class ETSignedOutAlertController: UIViewController {

    fileprivate var coverView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        return view
    }()
    
    fileprivate var panelView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 6
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOpacity = 0.3
        view.layer.shadowOffset = CGSize(width: 1, height: 1)
        view.backgroundColor = UIColor.white
        return view
    }()
    
    fileprivate var titleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont(name: "PingFangSC-Regular", size: 18)
        label.text = "您离开工地已经超时，是否忘记签出？需要一键签出吗？"
        label.textAlignment = .center
        return label
    }()
    
    fileprivate var signedOutButton: UIButton = {
        let button = UIButton()
        button.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 16)
        button.setTitleColor(UIColor.init(red: 61/255, green: 151/255, blue: 255/255, alpha: 1), for: .normal)
        button.setTitle("快速签出（）", for: .normal)
        
        return button
    }()
    
    fileprivate var descriptionLabel: UILabel = {
        let label = UILabel()
        label.text = "如果不操作，将自动签出"
        label.textAlignment = .center
        label.textColor = UIColor(red: 153/255, green: 153/255, blue: 153/255, alpha: 1)
        label.font = UIFont.init(name: "PingFangSC-Regular", size: 13)
        return label
    }()
    
    var timer: Timer!
    var timeOut: Int = 0
    //当前alert是否正在显示
    private var isShowing:Bool = false
    
    private var okHandler: (()->Void)?
    
    var demandBaseMigrantWorkerID: String?
    ///
    ///
    /// - Parameter okHandler: 当手动点击快速签出时会执行闭包。倒数时间结束不会执行闭包
    init (_  okHandler: @escaping ()-> Void){
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.okHandler = okHandler
    }
    
    init (demandBaseMigrantWorkerID: String?, timeOut: Int = 60) {
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.demandBaseMigrantWorkerID = demandBaseMigrantWorkerID
        self.timeOut = timeOut
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.signedOutButton.addTarget(self, action: #selector(doSignedOutButtonAction), for: .touchUpInside)
        
        self.setupViews()
        
        self.timer = Timer.init(timeInterval: 1, target: self, selector: #selector(doTimerAction(_:)), userInfo: nil, repeats: true)
        RunLoop.current.add(self.timer, forMode: .commonModes)
        
        self.isShowing = true
    }
    
    deinit {
        self.isShowing = false
    }

    private func setupViews() {
        self.view.addSubview(self.coverView)
        self.coverView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        self.view.addSubview(self.panelView)
        self.panelView.snp.makeConstraints { (make) in
            make.left.equalTo(45)
            make.right.equalTo(-45)
            make.center.equalTo(self.view)
        }
        
        self.panelView.addSubview(self.titleLabel)
        self.titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.panelView).offset(10)
            make.left.equalTo(self.panelView).offset(10)
            make.right.equalTo(self.panelView).offset(-10)
        }
        
        let horizontalLine1 = UIView()
        horizontalLine1.backgroundColor = UIColor(red: 243/255, green: 243/255, blue: 243/255, alpha: 1)
        self.panelView.addSubview(horizontalLine1)
        horizontalLine1.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.panelView)
        make.top.equalTo(self.titleLabel.snp.bottom).offset(5)
            make.height.equalTo(1)
        }
        
        self.panelView.addSubview(self.signedOutButton)
        self.signedOutButton.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.panelView)
            make.top.equalTo(horizontalLine1.snp.bottom).offset(10)
        }
        
        let horizontalLine2 = UIView()
        horizontalLine2.backgroundColor = UIColor(red: 243/255, green: 243/255, blue: 243/255, alpha: 1)
        self.panelView.addSubview(horizontalLine2)
        horizontalLine2.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.panelView)
            make.top.equalTo(self.signedOutButton.snp.bottom).offset(10)
            make.height.equalTo(1)
        }
        
        self.panelView.addSubview(self.descriptionLabel)
        self.descriptionLabel.snp.makeConstraints { (make) in
            make.top.equalTo(horizontalLine2.snp.bottom).offset(5)
            make.left.right.equalTo(self.panelView)
            make.bottom.equalTo(self.panelView).offset(-5)
        }
    }
    
    //点击签出按钮签出接口
    private func signedOut() {
        WWBeginLoadingWithStatus("正在签到")
        
        var guid: String?
        
        let _dispatchGroup = DispatchGroup()
        
        _dispatchGroup.enter()
        UserModel.getGuid { (response) in
            if response.success {
                guid = response.value
            }
            else{
                WWError(response.message)
            }
            _dispatchGroup.leave()
        }
        
        _dispatchGroup.notify(queue: DispatchQueue.main) {
            guard guid != nil else {
                WWError("guid是空的")
                return
            }
            guard self.demandBaseMigrantWorkerID != nil else{
                return
            }
            RecordModel.fastRecord(guid:guid!,demandBaseMigrantWorkerId: self.demandBaseMigrantWorkerID!, signedType: SignedType.signedOut){(response) in
                if response.success {
                    WWSuccess("签出成功")
                    NotificationCenter.default.post(name: NSNotification.Name.init(kNotificationAlertSignedInSignedOut), object: nil)
                }
                else {
                    WWError(response.message)
                }
            }
        }
    }
    
    //倒计时结束签出
    private func autoSignOut() {
        guard self.demandBaseMigrantWorkerID != nil else {
            return
        }
        
    RecordModel.signOutAutomatically(self.demandBaseMigrantWorkerID!) { (response) in
            if response.success {
                
            }
            else {
                
            }
        }
    }
    
    //如果手动点击签出，那么就需要调用签出接口，这点和时间结束后进行的操作是不同的。
    @objc private func doSignedOutButtonAction() {
        self.signedOut()
        
        if self.okHandler != nil {
            self.okHandler!()
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func doTimerAction(_ timer: Timer) {
        if self.timeOut <= 0 {
            self.autoSignOut()
            //倒数结束取消弹框，签出操作后台会执行
            self.dismiss(animated: true, completion: nil)
        }
        else {
            self.timeOut -= 1
            self.signedOutButton.setTitle("快速签出（\(self.timeOut)）", for: .normal)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.timer.invalidate()
    }
}


extension ETSignedOutAlertController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SignedOutAlertControllerTransitionPresent()
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SignedOutAlertControllerTransitionDismiss()
    }
}

class SignedOutAlertControllerTransitionPresent: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromView = transitionContext.view(forKey: .from)
        let toVc = transitionContext.viewController(forKey: .to) as! ETSignedOutAlertController
        let container = transitionContext.containerView
        container.addSubview(toVc.view)
        
        let panelView = toVc.panelView
        let coverview = toVc.coverView
        coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        panelView.alpha = 0.3
        panelView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
        UIView.animate(withDuration:0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.3)
            panelView.transform = CGAffineTransform.identity
            panelView.alpha = 1
        }) { (finish) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            toVc.view.addSubview(fromView!)
            toVc.view.sendSubview(toBack: fromView!)
        }
    }
}

class SignedOutAlertControllerTransitionDismiss: NSObject,UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromVc = transitionContext.viewController(forKey: .from) as! ETSignedOutAlertController
        
        //        let panelView = fromVc.panelView
        let coverview = fromVc.coverView
        UIView.animate(withDuration: 0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        }) { (_) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}
